/**
 * desc:http
 * author:Points
 * time:2019-01-18
 */

let app = getApp();
/**
 * 需要用到async/await的页面必须加此引入
 */
import regeneratorRuntime from './regenerator-runtime/runtime.js'

/**
 * post方法的url
 */
const URLS = {
  Activity: {
    List: 'activity/list'
  }
}


/**
 * 处理异常，抛给调用者具体信息
 */
const startPost = async(url,body)=>{
  try {
    const { state, value } = await post(app.globalData.SERVER + url,body)
      return { state: state, value: value }
  } catch (e) {
    console.log('startPost' + JSON.stringify(e));
    return { state: false, value: e }
  }
}

// /**
//  * 发起普通post请求
//  */
 const post= async (url,body)=>{
  return await new Promise((resove, reject) => {
    wx.request({
      url: url,
      data: body,
      method: 'POST',
      success: function (res) { 
        console.info('发起普通post请求成功'+url+JSON.stringify(body)+JSON.stringify(res));
        resove({ state: true, value: res })
      },
      fail: function (error) { 
        console.error('发起普通post请求失败' + url + JSON.stringify(body) + JSON.stringify(error));
        reject({ state: false, value: error })
      },
      complete: function (res) {

       },
    })
  })
}

/**
 * 本地设置缓存
 */
const setObjectToStorgeAsync= async (key,obj)=>{
  return await new Promise((resolve,reject)=>{
    wx.setStorage({
      key: key,
      data: obj,
      success: function (res) {
        resolve({state:true,value:res})
      },
      fail: function (err) {
        reject({state:false,value:err})
      }
    })
  })
}

const getObjectFromStorgeAsync = async (key) => {
  return await new Promise((resolve,reject)=>{
    try {
   wx.getStorage({
      key: key,
      success: function (res) {
        resolve({ state: true, value: res })
      },
      fail: function (err) {
        resolve({ state: false, value: err})
      }
    })
    }catch (e){
      reject({ state: false, value: e })
    }
  })
}

const getObjectFromStorgeSync =  (key) => {
  return wx.getStorageSync(key)
}

module.exports = {
   post: startPost,
   setObjectToStorgeAsync: setObjectToStorgeAsync,
   getObjectFromStorgeAsync: getObjectFromStorgeAsync,
   getObjectFromStorgeSync: getObjectFromStorgeSync,
   url_activityList: 'activity/list',
  KEYS: {
    SHOP: Symbol('shop').toString(),
  }
}